﻿#include "mainwindow.h"
#include "./ui_mainwindow.h"
#include <QFileDialog>
#include <QUrl>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    //设置 QPlainTextEdit 只读模式
    ui->plainTextEdit->setReadOnly(true);

    //设置 QTextBrowser 能自动用系统浏览器打开外站链接
    ui->textBrowser->setOpenExternalLinks(true);

    //将 "后退"、"前进"按钮设置为不可用状态
    ui->pushButtonBack->setEnabled(false);
    ui->pushButtonForward->setEnabled(false);

    //关联 "后退" 按钮的信号到对应槽函数
    connect(ui->pushButtonBack, &QPushButton::clicked, ui->textBrowser, &QTextBrowser::backward);
    //关联 "前进" 按钮的信号到对应槽函数
    connect(ui->pushButtonForward, &QPushButton::clicked, ui->textBrowser, &QTextBrowser::forward);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_pushButtonOpen_clicked()
{
    QUrl urlFile = QFileDialog::getOpenFileUrl(this, "open HTML", QUrl("file:///E:/"), "HTML files(*.htm *.html)");
    //URL 非空，才进行打开操作
    if( ! urlFile.isEmpty())
    {
        //打印文件链接
        qDebug()<<urlFile;
        //设置浏览的源文件
        ui->textBrowser->setSource(urlFile);
    }
}


void MainWindow::on_textBrowser_backwardAvailable(bool arg1)
{
    ui->pushButtonBack->setEnabled(arg1);
}


void MainWindow::on_textBrowser_forwardAvailable(bool arg1)
{
    ui->pushButtonForward->setEnabled(arg1);
}


void MainWindow::on_textBrowser_textChanged()
{
    //获取 html 字符串，设置给 plainTextEdit
    QString strHtml = ui->textBrowser->toHtml();
    ui->plainTextEdit->setPlainText(strHtml);
}

